package sys.spvisor.core.service.project;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import sys.spvisor.core.dao.project.TBigProjectMapper;
import sys.spvisor.core.dao.project.TFileFormMapper;
import sys.spvisor.core.dao.project.TProjectMapper;
import sys.spvisor.core.dao.project.TProjectPeopleMapper;
import sys.spvisor.core.dao.project.TSendCardMapper;
import sys.spvisor.core.entity.project.PushMessageCustom;
import sys.spvisor.core.entity.project.TBigProjectExample;
import sys.spvisor.core.entity.project.TFileForm;
import sys.spvisor.core.entity.project.TFileFormExample;
import sys.spvisor.core.entity.project.TBigProject;
import sys.spvisor.core.entity.project.TProject;
import sys.spvisor.core.entity.project.TProjectCustom;
import sys.spvisor.core.entity.project.TProjectExample;
import sys.spvisor.core.entity.project.TProjectExample.Criteria;
import sys.spvisor.core.entity.project.TProjectPeople;
import sys.spvisor.core.entity.project.TProjectPeopleExample;
import sys.spvisor.core.entity.project.TSendCard;
import sys.spvisor.core.entity.project.TSendCardExample;

@Service
public class ProjectService {
	
	@Autowired
	FileService fileService;
	
	@Autowired
	TFileFormMapper fileFormMapper;
	
	@Autowired
	TProjectPeopleMapper tProjectPeopleMapper;
	
	@Autowired
	TProjectMapper tProjectMapper;
	
	@Autowired
	TBigProjectMapper tBigProjectMapper;
	
	@Autowired
	PushMessageService pushMessageService;
	
	@Autowired
	TSendCardMapper tSendCardMapper;
	
	@Autowired
	UploadExcelService customerService;
	
	@Transactional
	//这个返回值用于标识导入物资清单是否成功
	public String addProject(TProjectCustom custom,Map<String, MultipartFile> fileMap,String userName,long userId) throws IOException {
		
		PushMessageCustom pushMessageCustom = new PushMessageCustom();
		
		int bigProjectId = 0;
		List<TBigProject> bigProjects = getAllBigProjectName();
		for (TBigProject tBigProject : bigProjects) {
			if(tBigProject.getBigProjectName().equals(custom.gettProject().getProBigProjectName())) {
				bigProjectId = tBigProject.getBigProjectId();
				break;
			}
		}
		if(bigProjectId == 0) {
			TBigProject bigProject = new TBigProject();
			bigProject.setBigProjectCreatePeople(userName);
			bigProject.setBigProjectCreatePeopleId((int)userId);
			bigProject.setBigProjectCreateTime(new Date(new java.util.Date().getTime()));
			bigProject.setBigProjectName(custom.gettProject().getProBigProjectName());
			tBigProjectMapper.insert(bigProject);
			bigProjectId = bigProject.getBigProjectId();
		}
		
		TProject record = custom.gettProject();
		record.setProCreateTime(new Date(new java.util.Date().getTime()));
		record.setProLastUpdateTime(new Date(new java.util.Date().getTime()));
		record.setProCreatePeople(userName);
		record.setProCreatePeopleId((int)userId);
		record.setProBigProjectId(bigProjectId);
		tProjectMapper.insert(record);
		
		pushMessageCustom.setProId(record.getProId());
		//设置接收人的角色信息
		pushMessageCustom.setRole("监理过程管理");
		pushMessageCustom.setSendpeoId((int)userId);
		pushMessageCustom.setSendPeoName(userName);
		pushMessageCustom.setMessage("设置你发送的信息");
		String fileNameTotal = custom.getFileNameTotal();
		//如果为空，说明这一次没有上传物资清单这个文件，否则，上传了
		String Msg = "";
		if(fileNameTotal != null){
			//如果需要传递文件，需要设置文件名称
			//可能会传递多个文件，用&进行分割
			String sendFileName = "监造委托书&监理委托单";
			String[] fileName = sendFileName.split("&");
			String[] name = fileNameTotal.split("&");
			//文件上传
			int index = 0;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				MultipartFile mf 	= entity.getValue();
				System.out.println(mf.getOriginalFilename());
				if(!mf.getOriginalFilename().equals("")){
					TFileForm tPlanForm = new TFileForm();
					System.out.println(mf.getOriginalFilename());
					System.out.println(mf.getName());
					tPlanForm.setFileFormFilename(mf.getOriginalFilename());
					tPlanForm.setFileFormContent(mf.getBytes());
					tPlanForm.setFileFormName(name[index]);
					tPlanForm.setFileFormPeople(userName);
					tPlanForm.setFileFormPeopleId((int)userId);
					tPlanForm.setFileFormDate(new Date(new java.util.Date().getTime()));
					tPlanForm.setFileFormProjectId(record.getProId());
					tPlanForm.setFileFormType("委托信息");
					//获取物资清单信息
					if(name[index].equals("监理物资清单") || name[index] == "监理物资清单") {
						//批量导入。参数：文件名，文件。
				        boolean b = customerService.batchImport(mf.getOriginalFilename(),mf);
				        if(b){
				             Msg ="批量导入EXCEL成功！";
				        }else{
				             Msg ="批量导入EXCEL失败！";
				        } 
				        System.out.println(Msg);
					}
					fileFormMapper.insert(tPlanForm);
					for (int i = 0; i < fileName.length; i++) {
						if(fileName[i].equals(name[index] ) ||fileName[i] == name[index]) {
							pushMessageCustom.setFileName(fileName[i]);
							pushMessageCustom.setFileId(tPlanForm.getFileFormId());
							//有文件，会发送多次信息，因为可能有多个文件
							pushMessageService.sendMessage(pushMessageCustom);
							//清空文件信息
							pushMessageCustom.setFileName(null);
							pushMessageCustom.setFileId(0);
						}
						
					}
				}
				index++;
			}
		} else {
			//发送信息
			pushMessageService.sendMessage(pushMessageCustom);
		}
		
		return Msg;
	}
	//修改委托信息
	@Transactional
	public void modifyEntrustingByMsgId(TProjectCustom custom,Map<String, MultipartFile> fileMap,String userName,long userId) throws IOException {
		
		int bigProjectId = 0;
		List<TBigProject> bigProjects = getAllBigProjectName();
		for (TBigProject tBigProject : bigProjects) {
			if(tBigProject.getBigProjectName().equals(custom.gettProject().getProBigProjectName())) {
				bigProjectId = tBigProject.getBigProjectId();
				break;
			}
		}
		if(bigProjectId == 0) {
			TBigProject bigProject = new TBigProject();
			bigProject.setBigProjectCreatePeople(userName);
			bigProject.setBigProjectCreatePeopleId((int)userId);
			bigProject.setBigProjectCreateTime(new Date(new java.util.Date().getTime()));
			bigProject.setBigProjectName(custom.gettProject().getProBigProjectName());
			tBigProjectMapper.insert(bigProject);
			bigProjectId = bigProject.getBigProjectId();
		}
		
		TProject record = custom.gettProject();
		record.setProLastUpdateTime(new Date(new java.util.Date().getTime()));
		record.setProCreatePeople(userName);
		record.setProCreatePeopleId((int)userId);
		record.setProBigProjectId(bigProjectId);
		tProjectMapper.updateByPrimaryKey(record);
		
		String fileNameTotal = custom.getFileNameTotal();
		System.out.println(fileNameTotal);
		if(fileNameTotal != null){
			String[] name = fileNameTotal.split("&");
			List<TFileForm> tFileForms = fileService.selectByMsgIdAndType(custom.gettProject().getProId(),"委托信息");		
			
			for(String n : name){
				for(TFileForm tFileForm : tFileForms){
					if(n.equals(tFileForm.getFileFormName())){
						tFileForms.remove(tFileForm);
						break;
					}
				}
			}
			
			for(TFileForm tFileForm : tFileForms){
				fileService.deleteByTypeAndNameAndMsgId(custom.gettProject().getProId(),"委托信息",tFileForm.getFileFormName());
			}
			
			//文件上传
			int index = 0;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
					
				MultipartFile mf 	= entity.getValue();
				System.out.println(mf.getOriginalFilename());
				if(!mf.getOriginalFilename().equals("")){
					TFileForm tPlanForm = new TFileForm();
					System.out.println(mf.getOriginalFilename());
					System.out.println(mf.getName());
					tPlanForm.setFileFormFilename(mf.getOriginalFilename());
					tPlanForm.setFileFormContent(mf.getBytes());
					tPlanForm.setFileFormName(name[index]);
					tPlanForm.setFileFormPeople(userName);
					tPlanForm.setFileFormPeopleId((int)userId);
					tPlanForm.setFileFormDate(new Date(new java.util.Date().getTime()));
					tPlanForm.setFileFormProjectId(record.getProId());
					tPlanForm.setFileFormCurrentStatusNum(0);
					tPlanForm.setFileFormCurrentStatus("D");
					tPlanForm.setFileFormType("委托信息");
					List<TFileForm> list = fileService.selectByMsgIdAndTypeAndName(record.getProId(),"委托信息", name[index]);
					if(list == null || list.size() == 0) {
						//如果是没修改，那么文件未通过次数为0
						tPlanForm.setFileFormNotpassTimes(0);
						fileFormMapper.insert(tPlanForm);
					} else {
						//如果是修改的，那么文件未通过次数+1
						//注意数据库FileFormNotpassTimes字段为空，会报错误
						tPlanForm.setFileFormNotpassTimes(list.get(0).getFileFormNotpassTimes() + 1);
						System.out.println(list.get(0).getFileFormId());
						tPlanForm.setFileFormId(list.get(0).getFileFormId());
						fileFormMapper.updateByPrimaryKey(tPlanForm);
					}
				}
				index++;
			}
		}
	}
	
	//查询相关子项目
	@Transactional
	 public List<TProject> selectByExample(TProject msg) {
		TProjectExample example = new TProjectExample();
		Criteria criteria = example.createCriteria();
		if(msg.getProBigProjectName() != null || msg.getProBigProjectName() != "") {
			criteria.andProBigProjectNameLike("%" +msg.getProBigProjectName()+"%");
		}
		if(msg.getProjectName() != null || msg.getProjectName() != "") {
			criteria.andProjectNameLike("%" +msg.getProjectName() +"%");
		}
		if(msg.getProNum() != null || msg.getProNum() != "") {
			criteria.andProNumLike("%" + msg.getProNum() + "%");
		}
		if(msg.getProConpeople() != null || msg.getProConpeople() != "") {
			criteria.andProConpeopleLike("%"+msg.getProConpeople()+ "%");
		}
		
		List<TProject> lists  =tProjectMapper.selectByExample(example);
		/*List<TMsg> lists = new ArrayList<TMsg>();
		TMsg msg2 = tMsgMapper.selectByPrimaryKey(19);
		lists.add(msg2);*/
		return lists;
		
	}
	
	@Transactional
	public TProject selectByPrimaryKey(Integer msgId) {
		TProject msg = tProjectMapper.selectByPrimaryKey(msgId);
		return msg;
		
	}
	
/*	public TProject selectBymsgId(Integer msgId) {
//		TMsg msg = tMsgMapper.selectByPrimaryKey(msgId);
		TProjectExample example = new TProjectExample();
		sys.spvisor.core.entity.project.TProjectExample.Criteria criteria = example.createCriteria();
		criteria.andProjectMsgidEqualTo(msgId);
		TProject project = tProjectMapper.selectByExample(example).get(0);
		return project;
		
	}
	*/
	//根据业主单位查询委托信息
	@Transactional
	public TProject viewProjectByUnitName(String unitName) {
		TProjectExample msgExample = new TProjectExample();
		Criteria criteria = msgExample.createCriteria();
		criteria.andProUnitLike("%" + unitName + "%");
		List<TProject> lists = tProjectMapper.selectByExample(msgExample);
		TProject msg = null;
		if(lists.size() > 0) {
			msg = lists.get(lists.size() - 1);
		}
		return msg;
	}
	
	@Transactional
	public List<TBigProject> getAllBigProjectName() {
		TBigProjectExample example = new TBigProjectExample();
		example.createCriteria();
		List<TBigProject> lists = tBigProjectMapper.selectByExample(example);
		return lists;
	}
	
	public String getProjectNameBymsgId(Integer proId){
		TProject pro = tProjectMapper.selectByPrimaryKey(proId);
		return pro.getProjectName();
	}
	
	//根据子项目id查找其对应的委托文件
		@Transactional
		public List<TFileForm> selectEntrustFileByProjectId(int msgId) {
			List<TFileForm> TFileForms = new ArrayList<TFileForm>();
			
			TFileFormExample example = new  TFileFormExample();
			sys.spvisor.core.entity.project.TFileFormExample.Criteria criteria = example.createCriteria();
			criteria.andFileFormProjectIdEqualTo(msgId);
			criteria.andFileFormTypeEqualTo("委托信息");
			List<TFileForm> selectTFileForms = fileFormMapper.selectByExample(example);
			addExistsFile("监造委托书",selectTFileForms,TFileForms);
			addExistsFile("监理服务合同",selectTFileForms,TFileForms);
			addExistsFile("监理委托单",selectTFileForms,TFileForms);
			addExistsFile("监理物资清单",selectTFileForms,TFileForms);
			addExistsFile("技术协议",selectTFileForms,TFileForms);
			//往TFileForms添加没有存储到数据库中的信息
			for(TFileForm tFileForm : selectTFileForms){
				TFileForms.add(tFileForm);
			}
			
			return TFileForms;
		}
		
		//往TFileForms添加已经存储在数据库中的文件信息
		private void addExistsFile(String fileName,List<TFileForm> selectTFileForms,List<TFileForm> TFileForms){
			for(TFileForm tFileForm : selectTFileForms){
				if(tFileForm.getFileFormName().equals(fileName)){
					TFileForms.add(tFileForm);
					selectTFileForms.remove(tFileForm);
					return;
				}
				
			}
			TFileForm fileForm = new TFileForm();
			fileForm.setFileFormName(fileName);
			TFileForms.add(fileForm);
		}
		
		public String getProjectNameBymsgId(int msgId){
			TProject tmsg = tProjectMapper.selectByPrimaryKey(msgId);
			return tmsg.getProjectName();
		}
		
		@SuppressWarnings("deprecation")
		public String getEncodeProjectNameBymsgId(Integer proId){
			TProject pro = tProjectMapper.selectByPrimaryKey(proId);
			return URLEncoder.encode(pro.getProjectName());
		}
		
		//根据项目id查询参与项目的相关人员
			@Transactional
			public List<TProjectPeople> getAllItemPeopleByProId (int proId){
				TProjectPeopleExample tProjectPeopleExample = new TProjectPeopleExample();
				sys.spvisor.core.entity.project.TProjectPeopleExample.Criteria criteria = tProjectPeopleExample.createCriteria();
				criteria.andPpMsgidEqualTo(proId);
				List<TProjectPeople> lists = tProjectPeopleMapper.selectByExample(tProjectPeopleExample);
				return lists;
				
			}
			
			//根据项目id查询项目所有的文件信息
			public List<TFileForm> getAllItemFileByProId(int proId) {
				TFileFormExample tFileFormExample = new TFileFormExample();
				sys.spvisor.core.entity.project.TFileFormExample.Criteria criteria = tFileFormExample.createCriteria();
				criteria.andFileFormProjectIdEqualTo(proId);
				List<TFileForm> lists = fileFormMapper.selectByExample(tFileFormExample);
				return lists;
				
			}
			
			//根据项目id查找其对应的派遣单信息
			public TSendCard getSendCardByProId(int proId) {
				TSendCardExample sendCardExample = new TSendCardExample();
				sys.spvisor.core.entity.project.TSendCardExample.Criteria criteria = sendCardExample.createCriteria();
				criteria.andTSendProjectIdEqualTo(proId);
				List<TSendCard> lists = tSendCardMapper.selectByExample(sendCardExample);
				return lists.get(0);
				
			}
			
			//添加或者修改开工报审资料
			public void addOrUpdateBeginWork(int proId,String fileNameTotal,Map<String, MultipartFile> fileMap, String userName,Long userId) throws IOException {
				if(fileNameTotal != null){
					String[] name = fileNameTotal.split("&");
					//文件上传
					int index = 0;
					for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
							
						MultipartFile mf 	= entity.getValue();
						System.out.println(mf.getOriginalFilename());
						if(!mf.getOriginalFilename().equals("")){
							TFileForm tPlanForm = new TFileForm();
							System.out.println(mf.getOriginalFilename());
							System.out.println(mf.getName());
							tPlanForm.setFileFormFilename(mf.getOriginalFilename());
							tPlanForm.setFileFormContent(mf.getBytes());
							tPlanForm.setFileFormName(name[index]);
							tPlanForm.setFileFormPeople(userName);
							tPlanForm.setFileFormPeopleId(userId.intValue());
							tPlanForm.setFileFormDate(new Date(new java.util.Date().getTime()));
							tPlanForm.setFileFormProjectId(proId);
							tPlanForm.setFileFormType("开工报审");
							tPlanForm.setFileFormCurrentStatus("W");
							tPlanForm.setFileFormCurrentStatusNum(0);
							List<TFileForm> list = fileService.selectByMsgIdAndTypeAndName(proId,"开工报审", name[index]);
							if(list == null || list.size() == 0) {
								//如果是新增的，那么文件未通过次数为0
								tPlanForm.setFileFormNotpassTimes(0);
								fileFormMapper.insert(tPlanForm);
							}
							else {
								//如果是修改的，那么文件未通过次数+1
								tPlanForm.setFileFormNotpassTimes(list.get(0).getFileFormNotpassTimes() + 1);
								tPlanForm.setFileFormId(list.get(0).getFileFormId());
								fileFormMapper.updateByPrimaryKey(tPlanForm);
							}
						}
						index++;
					}
				}
				
			}
			
			//查找开工报审资料
			public List<TFileForm> getBeginWorkByProId(int proId) {
				List<TFileForm> tFileForms = fileService.selectByMsgIdAndType(proId,"开工报审");	
				return tFileForms;
				
			}
			
	
}
